package cn.edu.zjx.controller;

import com.management.entity.Department;
import com.management.service.DepartmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    
    private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);
    
    @Autowired
    private DepartmentService departmentService;
    
    @GetMapping("/list")
    public String list(Model model) {
        try {
            model.addAttribute("departments", departmentService.getAllDepartments());
            return "department/list";
        } catch (Exception e) {
            logger.error("获取部门列表失败", e);
            model.addAttribute("error", "获取部门列表失败");
            return "error";
        }
    }
    
    @GetMapping("/add")
    public String add() {
        return "department/add";
    }
    
    @PostMapping("/add")
    @ResponseBody
    public String add(Department department) {
        return departmentService.addDepartment(department) ? "success" : "error";
    }
    
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        try {
            model.addAttribute("department", departmentService.getDepartmentById(id));
            return "department/edit";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "加载编辑页面失败");
            return "error";
        }
    }
    
    @PostMapping("/edit")
    @ResponseBody
    public String edit(Department department) {
        return departmentService.updateDepartment(department) ? "success" : "error";
    }
    
    @PostMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id) {
        return departmentService.deleteDepartment(id) ? "success" : "error";
    }
    
    @GetMapping("/search")
    public String search(String keyword, Model model) {
        try {
            model.addAttribute("departments", departmentService.searchDepartments(keyword));
            return "department/list";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "搜索部门失败");
            return "error";
        }
    }
} 